var mongoose = require('mongoose')
var Schema = mongoose.Schema

const readingSchema = Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  book: {
    type: Schema.Types.ObjectId,
    ref: 'Book'
  },
  progress: Number,
  section: Number,
  readtime: Number,
  created_at: Date,
  updated_at: Date
})

readingSchema.pre('save', function (next) {
  const reading = this
  if (!reading.isModified || !reading.isNew) {
    next()
  } else {
    const currentDate = new Date()
    reading.updated_at = currentDate
    if (!reading.created_at)
      reading.created_at = currentDate
    next()
  }
})

module.exports = mongoose.model('Reading', readingSchema)
